<template>
  <div class="index">
    <van-dropdown-menu ref="menuRef">
      <van-dropdown-item v-model="state.selectCqdd" :title="cqddTitle" :options="option1" @change="onChangeCqdd" />
      <van-dropdown-item :disabled="!state.selectCqdd" :title="jqzTitle" v-model="state.selectJqz" :options="option2"
        @change="onChangeJqz" />
      <van-dropdown-item :disabled="!state.selectJqz" :title="jingTitle" v-model="state.selectJing" :options="option3"
        @change="onChangeJing" />
    </van-dropdown-menu>

    <van-empty v-if="list.length === 0" description="" />

    <div v-else class="list">
      <div>
        <el-card class="item" v-for="item in list" :key="item.id" @click="onEdit(item)">
          {{ item.jingdetail }}
        </el-card>
      </div>
      <el-card>
        <el-form :model="formData" ref="formRef" size="large" label-width="80px">
          <van-button class="add-btn" plain type="primary" icon="plus" block @click="onAddJingItem">添加图片</van-button>
          <div v-for="(item, index) in formData.imgUrlList" :key="index" class="image-group">
            <div class="left">
              <el-form-item label="存在问题" :prop="'imgUrlList.' + index + '.remark'" :rules="rules.remark">
                <el-input v-model="item.remark" type="textarea" placeholder="请输入存在问题" />
              </el-form-item>
              <el-form-item label="图片" :prop="'imgUrlList.' + index + '.fileList'" :rules="rules.fileList">
                <van-uploader v-model="item.fileList" :after-read="(file) => afterRead(file, index)"
                  @delete="(file) => deleteFile(file, index)" />
              </el-form-item>
            </div>
            <div v-if="index !== 0" class="right" @click="onRemoveJingItem(index)">
              <van-icon name="delete-o" color="blue" size="20" />
            </div>
          </div>
        </el-form>
        <van-button type="primary" block @click="onSumbit">保 存</van-button>
      </el-card>
    </div>
    <el-dialog v-model="dialogVisible" width="70%">
      <img style="width: 100%;" :src="dialogImageUrl" alt="Preview Image" />
    </el-dialog>

    <van-popup v-model:show="showRight" position="right" :style="{ width: '100%', height: '100%' }">
      <div class="popup-box">
        <van-nav-bar :title="state.currentRow.jingdetail" left-text="返回" left-arrow @click-left="showRight = false" />
        <div class="popup-content">
          <el-form :model="jingFormData" :rules="jingRules" ref="jingFormRef" size="large" label-width="80px">
            <el-form-item label="巡井日期" prop="datejing">
              <el-input placeholder="请选择巡井日期" v-model="jingFormData.datejing" readonly @click="onShowPicker">
                <template #suffix>
                  <el-icon>
                    <Calendar />
                  </el-icon>
                </template>
              </el-input>
              <van-popup v-model:show="showPicker" destroy-on-close position="bottom">
                <van-date-picker :model-value="datePickerValue" @confirm="onConfirmDatePicker"
                  @cancel="showPicker = false" />
              </van-popup>
            </el-form-item>
            <el-form-item label="井口油压" prop="yy">
              <el-input v-model="jingFormData.yy" placeholder="请输入井口油压" @input="validateNumber('yy')">
                <template #suffix>
                  (Mpa)
                </template>
              </el-input>
            </el-form-item>
            <el-form-item label="顶部油压" prop="dbyy">
              <el-input v-model="jingFormData.dbyy" placeholder="请输入顶部油压" @input="validateNumber('dbyy')">
                <template #suffix>
                  (Mpa)
                </template>
              </el-input>
            </el-form-item>

            <el-form-item label="套压" prop="ty">
              <el-input v-model="jingFormData.ty" placeholder="请输入套压" @input="validateNumber('ty')">
                <template #suffix>
                  (Mpa)
                </template>
              </el-input>
            </el-form-item>
            <el-form-item label="温度" prop="wd">
              <el-input v-model="jingFormData.wd" placeholder="请输入温度" @input="validateNumber('wd')">
                <template #suffix>
                  (°C)
                </template>
              </el-input>
            </el-form-item>
            <el-form-item label="瞬时流量" prop="ll">
              <el-input v-model="jingFormData.ll" placeholder="请输入瞬时流量" @input="validateNumber('ll')">
                <template #suffix>
                  (m³/h)
                </template>
              </el-input>
            </el-form-item>

            <van-button class="add-btn" plain type="primary" icon="plus" block
              @click="onAddJingDetailItem">添加图片</van-button>
            <div v-for="(item, index) in jingFormData.imgUrlList" :key="index" class="image-group">
              <div class="left">
                <el-form-item label="存在问题" :prop="'imgUrlList.' + index + '.remark'" :rules="jingRules.remark">
                  <el-input v-model="item.remark" type="textarea" placeholder="请输入存在问题" />
                </el-form-item>
                <el-form-item label="图片" :prop="'imgUrlList.' + index + '.fileList'" :rules="jingRules.fileList">
                  <van-uploader v-model="item.fileList" :after-read="(file) => afterJingDetailRead(file, index)"
                    @delete="(file) => deleteJingDetailFile(file, index)" />
                </el-form-item>
              </div>
              <div v-if="index !== 0" class="right" @click="onRemoveJingDetailItem(index)">
                <van-icon name="delete-o" color="blue" size="20" />
              </div>
            </div>
          </el-form>
        </div>
        <van-button type="primary" block @click="onJingSumbit">保 存</van-button>
      </div>
    </van-popup>
  </div>
</template>

<script setup>
import { onMounted, ref, reactive, computed } from "vue";
import { ElMessage } from "element-plus";
import dayjs from "dayjs";
import Api from "@/api";
const option1 = ref([]);
const option2 = ref([]);
const option3 = ref([]);
const dialogImageUrl = ref('')
const dialogVisible = ref(false)
const showRight = ref(false)
const showPicker = ref(false);
const datePickerValue = ref([])
const state = reactive({
  selectCqdd: "",
  selectJqz: "",
  selectJing: '',
  type: 1,
  currentRow: {}
});
const list = ref([]);
const formData = ref({
  imgUrlList: [
    {
      remark: '',
      fileList: [],
      imgUrl: []
    }
  ]
})
const formRef = ref(null)
const jingFormData = ref({
  yy: '',
  ty: '',
  wd: '',
  ll: '',
  dbyy: '',
  remark: '',
  imgUrlList: [
    {
      remark: '',
      fileList: [],
      imgUrl: []
    }
  ]
})

const jingFormRef = ref(null)

const onAddJingItem = () => {
  formData.value.imgUrlList.push({
    remark: '',
    fileList: [],
    imgUrl: []
  })
}

const onAddJingDetailItem = () => {
  jingFormData.value.imgUrlList.push({
    remark: '',
    fileList: [],
    imgUrl: []
  })
}


const onRemoveJingItem = (index) => {
  formData.value.imgUrlList.splice(index, 1)
}

const onRemoveJingDetailItem = (index) => {
  jingFormData.value.imgUrlList.splice(index, 1)
}


const validateJingFiles = (rule, value, callback) => {
  const index = rule.field.split('.')[1]
  if (jingFormData.value.imgUrlList[index].fileList.length === 0) {
    callback(new Error('请上传图片'))
  } else {
    callback()
  }
}

const jingRules = {
  datejing: [
    { required: true, message: '请输入井口时间', trigger: 'blur' },
  ],
  yy: [
    { required: true, message: '请输入井口油压', trigger: 'blur' },
  ],
  dbyy: [
    { required: true, message: '请输入顶部油压', trigger: 'blur' },
  ],
  ty: [
    { required: true, message: '请输入套压', trigger: 'blur' },
  ],
  wd: [
    { required: true, message: '请输入温度', trigger: 'blur' },
  ],
  ll: [
    { required: true, message: '请输入瞬时流量', trigger: 'blur' },
  ],
  remark: [
    { required: true, message: "请输入存在问题", trigger: "blur" },
  ],
  fileList: [
    { required: true, validator: validateJingFiles, trigger: "change" },
  ],
}
const validateFiles = (rule, value, callback) => {
  const index = rule.field.split('.')[1]
  if (formData.value.imgUrlList[index].fileList.length === 0) {
    callback(new Error('请上传图片'))
  } else {
    callback()
  }
}

const rules = {
  remark: [
    { required: true, message: "请输入存在问题", trigger: "blur" },
  ],
  fileList: [
    { required: true, validator: validateFiles, trigger: "change" },
  ],
}
const cqddTitle = computed(() => {
  return (
    option1.value.find((item) => item.value === state.selectCqdd)?.text ||
    "请选择采气大队"
  );
});

const jqzTitle = computed(() => {
  return (
    option2.value.find((item) => item.value === state.selectJqz)?.text ||
    "请选择集气站"
  );
});

const jingTitle = computed(() => {
  return (
    option3.value.find((item) => item.value === state.selectJing)?.text ||
    "请选择井场"
  );
});


const onChangeCqdd = (value) => {
  state.selectJqz = "";
  option2.value = [];
  list.value = [];
  getJqzSelect(value);
};
const getCqddSelect = async () => {
  const { result } = await Api.getCqddSelect();
  option1.value = (result || []).map((item) => ({
    text: item.cqdd,
    value: item.id,
  }));
};

const getJqzSelect = async (id) => {
  const { result } = await Api.getJqzSelect({ cqddId: id });
  console.log(result);
  option2.value = (result || []).map((item) => ({
    text: item.jqz,
    value: item.id,
  }));
};

const getJingSelect = async () => {
  const { result } = await Api.getJingSelect({ cqddId: state.selectCqdd, jqzid: state.selectJqz });
  console.log(result);
  option3.value = (result || []).map((item) => ({
    text: item.jing,
    value: item.id,
  }));
};

const getJingDetailSelect = async () => {
  const { result } = await Api.getJingDetailSelect({
    cqddId: state.selectCqdd,
    jqzid: state.selectJqz,
    jingid: state.selectJing,
  });
  list.value = (result || []);
}

const onChangeJing = () => {
  getJingDetailSelect()
}


const onSumbit = () => {
  const formatImgUrlList = () => {
    return formData.value.imgUrlList.map(item => ({ remark: item.remark, imgUrl: item.imgUrl.join(',') }))
  }
  formRef.value.validate(valid => {
    if (valid) {
      const params = {
        id: state.selectJing,
        imgUrlList: formatImgUrlList(),
      }
      Api.saveJingValue(params).then(res => {
        ElMessage.success({
          message: '保存成功',
          duration: 1000,
        });
        formData.value.imgUrlList = [{
          remark: '',
          fileList: [],
          imgUrl: []
        }];
      })
    } else {
      console.log('error submit!!');
      return false;
    }
  });
}


const onJingSumbit = () => {
  jingFormRef.value.validate(valid => {
    if (valid) {
      const formatImgUrlList = () => {
        return jingFormData.value.imgUrlList.map(item => ({ remark: item.remark, imgUrl: item.imgUrl.join(',') }))
      }
      const params = {
        id: state.currentRow.id,
        yy: jingFormData.value.yy,
        ty: jingFormData.value.ty,
        wd: jingFormData.value.wd,
        ll: jingFormData.value.ll,
        datejing: jingFormData.value.datejing,
        dbyy: jingFormData.value.dbyy,
        imgUrlList: formatImgUrlList()
      }
      Api.saveJingDetailValue(params).then(res => {
        ElMessage.success({
          message: '保存成功',
          duration: 1000,
        });
        showRight.value = false;
        jingFormData.value = {
          yy: '',
          ty: '',
          wd: '',
          ll: '',
          datejing: '',
          dbyy: '',
          imgUrlList: [
            {
              remark: '',
              fileList: [],
              imgUrl: []
            }
          ]
        }
      })
    } else {
      console.log('error submit!!');
      return false;
    }
  });
}

const validateNumber = (field) => {
  // 移除非数字和点的字符，并确保只有一个点
  jingFormData.value[field] = jingFormData.value[field]
    .replace(/[^\d.]/g, '') // 移除非数字和非点字符
    .replace(/(\..*)\./g, '$1'); // 确保只有一个点
}


const onEdit = (row) => {
  state.currentRow = row
  showRight.value = true
}

const onShowPicker = () => {
  datePickerValue.value = [dayjs().format('YYYY'), dayjs().format('MM'), dayjs().format('DD')]
  showPicker.value = true
}

const onConfirmDatePicker = ({ selectedValues }) => {
  jingFormData.value.datejing = selectedValues.join('-')
  showPicker.value = false
  jingFormRef.value.validateField('datejing')
}


const afterRead = (file, index) => {
  const form = new FormData();
  form.append('file', file.file);
  Api.uploadFile(form).then(res => {
    formData.value.imgUrlList[index].imgUrl.push(res.result)
    file.responseUrl = res.result
  })
}


const deleteFile = (file, parentIndex) => {
  const imgUrls = formData.value.imgUrlList[parentIndex].imgUrl;
  const index = imgUrls.findIndex(url => url === file.responseUrl);
  if (index !== -1) {
    imgUrls.splice(index, 1);
  }
}


const afterJingDetailRead = (file, index) => {
  const form = new FormData();
  form.append('file', file.file);
  Api.uploadFile(form).then(res => {
    jingFormData.value.imgUrlList[index].imgUrl.push(res.result)
    file.responseUrl = res.result
  })
}


const deleteJingDetailFile = (file, parentIndex) => {
  const imgUrls = jingFormData.value.imgUrlList[parentIndex].imgUrl;
  const index = imgUrls.findIndex(url => url === file.responseUrl);
  if (index !== -1) {
    imgUrls.splice(index, 1);
  }
}


const onChangeJqz = () => {
  getJingSelect()
};

onMounted(() => {
  getCqddSelect();
});
</script>

<style scoped lang="scss">
.add-btn {
  margin-bottom: 10px;
}

.button-group {
  padding: 10px;

  .btn-item {
    margin-bottom: 10px;
  }
}

.edit-box {
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;

  .card {
    width: 85%;
  }
}

.list {
  padding: 10px;

  .item {
    margin-bottom: 10px;
  }
}

.custom {
  :deep(.el-upload--picture-card) {
    --el-upload-picture-card-size: 80px;
  }

  :deep(.el-upload-list--picture-card .el-upload-list__item) {
    --el-upload-picture-card-size: 80px;
    width: var(--el-upload-picture-card-size);
    height: var(--el-upload-picture-card-size);
  }

  :deep(.el-icon--close-tip) {
    display: none;
  }
}

.popup-box {
  height: 100%;
  display: flex;
  flex-direction: column;

  .popup-content {
    flex: 1;
    box-sizing: border-box;
    padding: 10px 10px 0 10px;
    overflow: scroll;
  }
}

.image-group {
  display: flex;

  .left {
    flex: 1;
  }

  .right {
    flex-basis: 30px;
    text-align: right;
  }
}
</style>
